package com.meiqiang.agent.retransform;

import com.meiqiang.po.Fruit;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;

/**
 * redefineClasses，通俗点来讲的话就是实现指定类的替换
 *
 * @author : zhengmeiqiang
 * @date : 2024/11/8 14:29
 */
public class RedefineAgent {

    public static void agentmain(String agentArgs, Instrumentation inst)
            throws Exception {

        if (agentArgs == null || "".equals(agentArgs)) {
            System.out.println("agentArgs is null");
            return;
        }
        String[] split = agentArgs.split("\\|");
        for (String s : split) {
            String[] clazz = s.split(",");
            String classFullName = clazz[0];
            String classPath = clazz[1];
            for (Class loadedClass : inst.getAllLoadedClasses()) {
                if (loadedClass.getName().equals(classFullName)){
                    File file = new File(classPath);
                    byte[] bytes = fileToBytes(file);
                    ClassDefinition classDefinition = new ClassDefinition(loadedClass, bytes);
                    inst.redefineClasses(classDefinition);
                    System.out.println("redefineClasses success,classFullName="+classFullName);
                }
            }
        }


    }

    private static byte[] fileToBytes(File file) throws IOException {
        FileInputStream in = new FileInputStream(file);
        byte[] bytes = new byte[in.available()];
        in.read(bytes);
        in.close();
        return bytes;
    }
}
